#!/usr/bin/perl -w
use strict;
use 5.010;
use autodie;
use Cwd;
use File::Spec;
my $path_curf = File::Spec->rel2abs(__FILE__);
#print "C PATH = ",$path_curf,"\n";
my ($vol, $dirs, $file) = File::Spec->splitpath($path_curf);
#print "C Dir = ", $dirs,"\n";

##read id => phyId maps
#my $scriptdir = getcwd;
my $mapfile = $dirs .  "map.txt";
#say $mapfile;
if ( ! -e $mapfile ){
  say "$mapfile not exist";
  exit 100;
}

open MAP,"<$mapfile" or die "cannnot open $mapfile : $!";
my %index;  #id => phyId;
#say "Existing maps:";
while(<MAP>){
  chomp;
  my @rs = split /\s+/,$_;
  if (defined $rs[0]){
    $index{$rs[0]} = $rs[1];
    #say "$rs[0] $rs[1]";
  }
}
close MAP;

my $motelist = $dirs . "motelist.txt";
system( "motelist -usb > $motelist" );
open MOTELIST,"<$motelist";
my %usbs ;
while (<MOTELIST>){
  chomp;
  my @rs = split /\s+/,$_;

  if (scalar @rs < 6){
    say $_;
    exit 3;
  }


  if ( $rs[5] =~ /ttyUSB/ ){
    my $port = (join '',($rs[5] =~ /\d+/g));
    my $phyId = $rs[4];
    $usbs{$phyId} = $port;
  }
}
close MOTELIST;

##
#say "ID PHYID PORT";
for my $k ( sort keys %index ){
  if ( defined $usbs{$index{$k}} ){
    say "$k $index{$k} $usbs{$index{$k}}";
  }
}
